package customer

import (
	"air_chat/common/global"
	"air_chat/internal/wscore"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// 防止跨域站点伪造请求
var upgrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SendMsg(c *gin.Context) {
	ws, err := upgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		global.ZAPLOGGER.Sugar().Errorf("升级为websocket失败：%v", err)
		return
	}
	defer ws.Close()

	msgHandler(ws, c)
}

func msgHandler(ws *websocket.Conn, c *gin.Context) {

	msg, err := global.Subscribe(c, global.PublishKey)
	if err != nil {
		global.ZAPLOGGER.Sugar().Errorf("订阅redis消息失败：%v", err)
		return
	}
	nowTime := time.Now().Format("2006-01-02 15:04:05")
	message := fmt.Sprintf("[ws][%v]:%v", nowTime, msg)
	err = ws.WriteMessage(1, []byte(message))
	if err != nil {
		global.ZAPLOGGER.Sugar().Errorf("发送消息失败：%v", err)
		return
	}
}

func ImChat(c *gin.Context) {
	wscore.AirChat(c.Writer, c.Request)
}
